# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem
  
  before_filter :set_user_time_zone
  
  helper :all # include all helpers, all the time
  
  helper_method :current_account
  
  # Set layout for application
  layout :set_layout

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery :only => [:create, :update, :destroy]# :secret => 'f9d3729f79106eb26c2268e05ae4e488'
  
  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  # filter_parameter_logging :password 
  
  protected
 
  # Before filter for controllers when admin user is required
  def admin_required
    current_user.respond_to?('admin') && current_user.send('admin')
  end
  
  # Before filter for controllers when superior is required
  def superior_required
    current_user.respond_to?('superior') && current_user.send('superior')
  end
  
  # Find current account by subdomain
  def current_account
    @account ||= Company.find_by_subdomain(current_subdomain)
  end
  
  # Before filter for user_not_required
  def user_not_required
    admin_required && superior_required
  end
  
  # Before filter for controllers when account_key is required
  def account_required
    unless current_account
      flash[:error] = "Tälle sivulle vaaditaan tili"
      redirect_to :controller => 'home', :action => 'index', :subdomain => false
    end
  end
  
  # Set time zone for current user
  def set_user_time_zone
    Time.zone = current_user.time_zone if logged_in?
  end
  
  # This application uses three different layouts.
  # Default application layout is used when a user is not logged in or subdomains hasn't been set.
  # Admins and normal users have own layouts.
  def set_layout
    return "application" unless current_account
    if logged_in? && current_account
      "admin/admin"
    elsif !logged_in?
      "login"
    end
  end
end
